<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/5/5
 * Time: 14:43
 */

namespace app\admin\controller;

use app\admin\model\AuthGroup;
use think\Db;
use app\admin\model\AuthRule;
use think\Cache;

class Role extends Admin
{
    /**
     * 角色组列表
     * @return mixed
     */
    public function index()
    {
        $auth_group = model('auth_group')->select();
        $this->assign('auth_group', $auth_group);
        return $this->fetch();
    }

    /**
     * 添加角色
     * @return mixed
     */
    public function add_role()
    {
        return $this->fetch('add');
    }

    /**
     *保存添加角色
     */
    public function add_rolerun()
    {
        if (!request()->isAjax()) {
            $this->error('提交方式不正确', url('admin/role/index'));
        } else {
            $menu = new AuthGroup();
            $data = input('post.');
            $arr = session('admin_user');
            logdaily(6,$arr['username'],'新增角色：'.$data['title']);
            $result = $menu->validate('authGroup')->allowField(true)->save($data);
            if (false === $result) {
                // 验证失败 输出错误信息
                $this->error($menu->getError());
            } else {
                $this->success('用户组添加成功', url('admin/role/index'));
            }
        }
    }

    /**
     * 编辑角色
     * @return mixed
     */
    public function edit_role()
    {
        input('id') ? $id = input('id') : $this->error('缺少参数');
        $info = Db::name('AuthGroup')->where(['id' => $id])->find();
        $arr = session('admin_user');
        logdaily(7,$arr['username'],'修改角色：'.$info['title']);

        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     *保存编辑角色
     */
    public function edit_rolerun()
    {
        if (!request()->isAjax()) {
            $this->error('提交方式不正确', url('admin/role/index'));
        } else {
            $menu = new AuthGroup();
            $data = input('post.');
            !empty($data['status']) ?: $data['status'] = 0;
            $result = $menu->allowField(true)->validate(true)->isUpdate(true)->save($data);
            if ($result !== false) {
                $this->success('用户组修改成功', url('admin/role/index'));
            } else {
                // 验证失败 输出错误信息
                $this->error($menu->getError());
            }
        }
    }

    /**
     * 删除角色
     * @return \think\response\Json
     */
    public function del_role()
    {
        $id = $this->request->param('id', 0);
        $info = Db::name('AuthGroup')->where(['id' => $id])->find();
        $arr = session('admin_user');
        logdaily(8,$arr['username'],'删除角色：'.$info['title']);
        if (empty($id)) {
            $this->error('请选择要操作的数据!');
        }
        if (AuthGroup::destroy($id)) {
            $arr = ['status' => 1, 'info' => '删除成功'];
        } else {
            $arr = ['status' => 0, 'info' => '删除失败'];
        }
        return json($arr);
    }

    /**
     *角色授权
     */
    public function role_group_access()
    {
        $admin_group = Db::name('auth_group')->where(array('id' => input('id')))->find();
        $data = AuthRule::get_ruels_tree();
        $this->assign('admin_group', $admin_group);
        $this->assign('datab', $data);
        return $this->fetch();
    }

    /**
     * 角色授权配置保存
     */
    public function role_group_runaccess()
    {
        $new_rules = input('new_rules/a');
        $imp_rules = implode(',', $new_rules);
        $data = array(
            'id' => input('id'),
            'rules' => $imp_rules,
        );
        $menu = new AuthGroup();
        $result = $menu->allowField(true)->validate("AuthGroup.edit")->isUpdate(true)->save($data);
        if ($result !== false) {
            Cache::clear();
            $this->success('权限配置成功', url('admin/role/index'));
        } else {
            $this->error($menu->getError());
        }
    }

    /**
     * 获取所有的状态
     * @return false|\PDOStatement|string|\think\Collection
     * @author: Huang
     * @internal
     */
    public function getStateIds()
    {
        $ids = Db::name('state')->select();
        return $ids;
    }

    /**
     * 状态授权给角色
     * @return mixed
     * @internal
     */
    public function stateDist()
    {
        $auth_id = input('id', 0, 'int');
        $authgroup = Db::name('auth_group')->where(['id' => $auth_id])->find();//当前角色
        $statusdata = Db::name('state')->select();//获取所有的状态
        $authcahzia = StatusGroup::where('auth_id', $auth_id)->column('status_id');//获取所有已经授权的状态id
        $this->assign('statedata', $statusdata);
        $this->assign('auth', implode(',', $authcahzia));
        $this->assign('authgroup', $authgroup);
        return $this->fetch();
    }

    /**
     * 将状态添加到角色组,入参auth_id,status_id
     * @internal
     */
    public function addToGroup()
    {
        $auth_id = $this->request->post('auth_id');
        $status_id = $this->request->post('status_id/a');
        if (empty($auth_id)) {
            $this->error('参数丢失');
        }
        $statusgroup = new StatusGroup();
        if (is_numeric($auth_id)) {
            if (!AuthGroup::get(array('id' => $auth_id))) {
                $this->error('角色不存在！');
            }
        }
        if ($statusgroup->addToGroup($auth_id, $status_id)) {
            Cache::clear('state');
            $this->success('操作成功');
        } else {
            $this->error($statusgroup->getError());
        }
    }


    /**
     * 设置角色对状态的权限和 电话的加密
     * @return mixed
     */
    public function setStates()
    {
        if ($this->request->isPost()) {
            $authdata = $this->request->post();
            if (empty($authdata['auth_id'])) {
                $this->error('参数丢失');
            } elseif (is_numeric($authdata['auth_id'])) {
                if (!AuthGroup::get(array('id' => $authdata['auth_id']))) {
                    $this->error('角色不存在！');
                } else {
                    $data['id'] = $authdata['auth_id'];
                    $data['caneditstates'] = implode(',', $authdata['caneditstates']);
                    $data['editstates'] = implode(',', $authdata['editstates']);
                    $data['baomi'] = intval($authdata['baomi']);
                    $data['hidstates'] = implode(',', $authdata['hidstates']);
                    $res = model('auth_group')->allowField(true)->isUpdate()->save($data);
                    if ($res) {
                        $this->success('操作成功');
                    } else {
                        $this->error(model('auth_group')->getError());
                    }
                }
            }
        } else {
            $auth_id = input('id', 0, 'int');
            $authgroup = Db::name('auth_group')->where(['id' => $auth_id])->find();//当前角色
            $statusdata = Db::name('state')->cache(6000)->select();//获取所有的状态
            $this->assign('statedata', $statusdata);
            $this->assign('authgroup', $authgroup);
            return $this->fetch();
        }
    }

    /**
     * 设置角色和部门，职位绑定
     * @return mixed
     * @author: Huang
     */
    public function setDeparandPosition()
    {
        $this->getDepar();
        input('id') ? $id = input('id') : $this->error('缺少参数');
        $info = Db::name('auth_group')->where('status',1)->where('id',$id)->find();
        $middle = Db::name('authgroup_depar_position')->where('auth_id',$id)->find();
        $this->assign('info',$info);
        $this->assign('middle',$middle);
        return $this->fetch('setdepar');
    }

    /**
     *保存部门和职位角色之间的关系
     */
    public function saveDeparPosition()
    {
        $data = input('post.');
        $info = Db::name('authgroup_depar_position')->where('auth_id',$data['auth_id'])->find();
        if($info==null){
           $re= Db::name('authgroup_depar_position')->insert($data);
           if($re){
               $this->success('新增成功！','index');
           }else{
               $this->error('新增失败！','index');
           }
        }else{
            $re= Db::name('authgroup_depar_position')->where('auth_id',$data['auth_id'])->update($data);
            if($re){
                $this->success('更新成功！','index');
            }else{
                $this->error('更新失败！','index');
            }
        }
    }
    /**
     * 获取公共部门方法
     * @internal
     */
    public function getDepar()
    {
        $depar_logic = new \app\admin\logic\Depar();
        $data = $depar_logic->getAllDeparToTree();
        $this->assign('depar', $data);
        $position = Db::name('position')->where('status',1)->select();
        $this->assign('position', $position);
    }
}